<?php
require('./wp-config.php');
require('./wp-blog-header.php');

if(isset($_GET['txtTagCondition']) && isset($_GET['txtTagPostCount'])) {
	$hitConditions = $_GET['txtTagCondition'];
	$tagCount = $_GET['txtTagPostCount'];
	
	$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	mysql_select_db(DB_NAME);
	
	// Select all postId, search query, search hits with search hist > x, x=5
	$sql = "SELECT id,PostId, SeQuery, SeHits FROM  wp_seobooster WHERE SeHits >= {$hitConditions}";
	
	$rows = mysql_query($sql, $conn);
	while($row = mysql_fetch_assoc($rows)) {
		// Get metadata to create a tag
		$tagname = $row['SeQuery'];
		$postId = $row['PostId'];
		$id = $row['id'];
		// Check exist post
		if(get_post($postId)) {
			// Check is match conditions
			// Get post view
			$count_key = 'post_views_count';
 
		    //Returns values of the custom field with the specified key from the specified post.
		    $count = get_post_meta($postId, $count_key, true);
		    
			if(!is_array(term_exists($tagname, 'post_tag')) && count($tags < $tagCount)) {
				// Insert new tag
				wp_set_post_tags($postId,$tagname, true);
				
				// Remove in seo booster table
				$sql = "DELETE * from wp_seobooster WHERE id={$id}";
				mysql_query($sql);
				
				mysql_close($conn);
				
			} else {
				echo "Tag <b>" . $tagname . "</b> already exist";
				echo "</br>";
			}
		} else {
			echo 'Missing post id = ' . $postId;
		}
	}
} else {
?>
<style>
<!--
label.left { width: 270px; float:left; }
-->
</style>
<h2> Seo Booster Pro auto Tag </h2>
<form method="get">
	<label class="left">Auto insert tag when user hit to post</label>
	<input type="text" name="txtTagCondition" value="5" />
	<br>
	<label class="left">Don't insert when post have enough tags</label>
	<input type="text" name="txtTagPostCount" value="20" />
	<br>
	<div style="clear:both"></div>
	<input type="submit" value="Submit" />
</form>
<?php } ?>